package cn.itcast.web_07.session.example01;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class CartServlet
 */
public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    // 处理响应中文的乱码
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        // 1、得到购物车
        List<Book> cart = null;
        // 2、得到自己的session
        HttpSession session = request.getSession();
        // 3、自己定义一个flag标识，判断购物车里是否有图书
        // true代表有图书
        boolean cartFlag = true;
	    if (session == null) {
	        cartFlag = false;
	    } else {
	        // 之前定义的键叫cart
	        cart = (List<Book>) session.getAttribute("cart");
	    }
	    // 4、购物车里有商品
	    if (!cartFlag) {
	        out.print("对不起，你的购物车里没有商品");
	    } else {
	        // 购物车里有图书
	        out.print("购买图书如下：" + "<br>");
	        for (Book b : cart) {
	            out.print("购买的图书：" + b.getName() + "<br>");
	        }
	    }
	    
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
